﻿using Microsoft.AspNetCore.SignalR;
using OA.Infrastructure.Abstractions;
using OA.Infrastructure.DomainModels;
using OA.Infrastructure.DomainModels.TemporaryAuthorization;
using OA.Infrastructure.SignalR.Abstractions;
using OA.Infrastructure.SignalR.Hubs;
using Quartz;

namespace AMS.Services.Job;

[DisallowConcurrentExecution]
internal class CleanTemporaryAuthorizationRoleJob : IJob
{
    private readonly DbContext _ctx;
    private readonly ISignalRService _signalRService;
    private readonly IWeComService _weComService;

    public int Id { private get; set; }
    public string Commiter { private get; set; } = null!;
    public string RequireContent { private get; set; } = null!;

    public CleanTemporaryAuthorizationRoleJob(DbContext ctx, ISignalRService signalRService, IWeComService weComService)
    {
        _ctx = ctx;
        _signalRService = signalRService;
        _weComService = weComService;
    }

    public async Task Execute(IJobExecutionContext context)
    {
        var entity = await _ctx.Set<Role>().FindAsync(new object[] { Id }, context.CancellationToken);

        if (entity is not null)
        {
            _ctx.Set<Role>().Remove(entity);
        }

        await _ctx.SaveChangesAsync(context.CancellationToken);

        await _signalRService.Factory
            .CreateGenericFactory<NotifyHub>()
            .CreateUserProxy(Commiter)
            .SendAsync("PermissionTemporaryAuthorization", new MessageRecord<TemporaryAuthorizationRecord>
            {
                Sender = "System",
                Data = new TemporaryAuthorizationRecord
                {
                    Status = -1,
                    Description = $"您申请的临时权限（{RequireContent}）已过期"
                }
            }, context.CancellationToken);

        await _weComService.SendTextMessageAsync(context.MergedJobDataMap.GetString("UserId")!, $"您申请的临时权限（{RequireContent}）已过期");
    }
}